class Utils {
  query(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
      return decodeURIComponent(r[2]);
    return null;
  }

  setItem(key, value) {
    localStorage.setItem(
      key,
      value.constructor == Object || value.constructor == Array
        ? JSON.stringify(value)
        : value
    )
  }

  getItem(key) {
    return localStorage.getItem(key) == null ? false : JSON.parse(localStorage.getItem(key))
  }

  initSocket() {
    window.sc = io(config.socketBaseUrl);
  }

  timestamp() {
    return new Date().getTime()
  }

  format(fmt, time) {
    time = new Date(time)
    var o = {
      "M+": time.getMonth() + 1,                 //月份
      "d+": time.getDate(),                    //日
      "h+": time.getHours(),                   //小时
      "m+": time.getMinutes(),                 //分
      "s+": time.getSeconds(),                 //秒
      "q+": Math.floor((time.getMonth() + 3) / 3), //季度
      "S": time.getMilliseconds()             //毫秒
    };

    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }

    return fmt;
  }

  async imgToBase64(url) {
    var file = await getFileFromUrl(url);
    var reader  = new FileReader();
    return new Promise((resolve, reject) => {
      reader.addEventListener("load", function () {
        var base64gif = reader.result; 
        resolve(base64gif)
      }, false);

      if (file) {
        reader.readAsDataURL(file);
      }
    })

    

    
  }

  getFileFromUrl(url) {
    let fileName = url.substr(url.lastIndexOf(".") -1 )
    let type = url.match(/\.(\w+)$/)[1]
    console.log(type);

    return new Promise((resolve, reject) => {
      var blob = null;
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.setRequestHeader('Accept', `image/${type}`);
      xhr.responseType = "blob";
      // 加载时处理
      xhr.onload = () => {
        // 获取返回结果
        blob = xhr.response;
        let file = new File([blob], fileName, { type: `image/${type}` });
        // 返回结果
        resolve(file);
      };
      xhr.onerror = (e) => {
        reject(e)
      };
      // 发送
      xhr.send();
    });
  }
}

let {
  query, setItem, getItem, initSocket, timestamp, format,
  imgToBase64, getFileFromUrl
} = new Utils()

initSocket()

